var mongoose = require('mongoose');
var assert = require('assert');

var Dishes = require('./models/dishes');

//Connection URL
var url = 'mongodb://localhost:27017/conFusion';
mongoose.connect(url);

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'console error: '))

db.once('open', function() {
    //we're connected!
    console.log('Connected correctly to server');

    //Create a new dish
    Dishes.create({
        "name": "Uthapizza1",
        "image": "images/uthapizza.png",
        "category": "mains",
        "label": "Hot",
        "price": "4.99",
        "description": "A unique . . .",
        "comments": [{
                "rating": 5,
                "comment": "Imagine all the eatables, living in conFusion!",
                "author": "John Lemon"
            },
            {
                "rating": 4,
                "comment": "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                "author": "Paul McVites"
            }
        ]
    }, function(err, dish) {
        if (err) throw err;

        console.log('Dish created!');
        console.log(dish);

        var id = dish._id;

        console.log('\n\n\n');
        //get all the dishes
        setTimeout(function() {
            Dishes.findByIdAndUpdate(id, {
                    $set: {
                        description: "Updated a unique...",
                        label: '',
                        price: '5.99'
                    }
                }, {
                    new: true
                })
                .exec(function(err, dish) {
                    if (err) throw err;
                    console.log('Updated Dish,description and label and price!!!');
                    console.log(dish);

                    console.log('\n\n\n');

                    dish.comments.push({
                        rating: 5,
                        comment: 'it is good',
                        author: 'tancolo'
                    });

                    dish.save(function(err, dish) {
                        console.log('Updated Comments!');
                        console.log(dish);
                        console.log('\n\n\n');

                        db.collection('dishes').drop(function() {
                            db.close();
                        })
                    })
                })
        })
    })
})